# -*- coding: utf-8 -*-
""" Image related utilities
"""
from gtk import gdk
from PIL import Image, ImageDraw

import tilecalc

def tile_mask(tile_size, total_size, tile_spc, offset):
    pass
#     for (x,y), (w,h) in tilecalc.gen_tiles_rect2D(self.tile_size,
#                                                   self.total_size,
#                                                   self.tile_spc,
#                                                   self.offset):
#         bm = Image.new('1'

def checkerboard(size=5,color1=(200,200,200), color2=(128,128,128)):
    """ Return a checkerboard pattern tile.
    """
    im = Image.new('RGB', (size*2, size*2), color2)
    draw = ImageDraw.Draw(im)
    draw.rectangle((0,0,size-1,size-1), color1)
    draw.rectangle((size,size,size**2,size**2), color1)
    return im


def diagonal_stripes(color=(128,128,128)):
    """ Return a diagonal striped pattern tile.
    """
    im = Image.new('RGBA', (3,3))
    ImageDraw.Draw(im).line((0,0, 3,3), color=color, width=1)
    return im


def pil_to_pixbuf(im):
    """ Convert a PIL image to a gdk.Pixbuf object """
    w, h = im.size
    alpha = im.mode == 'RGBA'
    return  gdk.pixbuf_new_from_data(im.tostring(),
                                     gdk.COLORSPACE_RGB,
                                     alpha, 8,
                                     w, h,
                                     w*len(im.mode))


def pil_to_pixmap(im, mask=False):
    """ Convert a PIL image to a gdk.Pixmap. If mask is given and is
    True, a tuple (pixmap, mask) is returned.
    """
    pm_and_mask = pil_to_pixbuf(im).render_pixmap_and_mask()
    if mask:
        return pm_and_mask
    else:
        return pm_and_mask[0]

def pixbuf_to_pil(pb):
    """Convert a gtk.Pixbuf to a PIL Image.
    """
    mode = "RGBA" if pb.get_has_alpha() else "RGB"
    im = Image.frombuffer(mode,
                          (pb.get_width(), pb.get_height()),
                          pb.get_pixels())

    return im.transpose(Image.FLIP_TOP_BOTTOM)

def _cprod(it1, it2):
    """ Cartesian product between two iterators """
    return ((a,b) for a in it1 for b in it2)


def make_color_transparent(im, color):
    """ Makes transparent every ocurrence of 'color' on the image """
    im = im.convert('RGBA')
    pixels = im.load()
    for (x,y) in _cprod(xrange(im.size[0]), xrange(im.size[1])):
        if pixels[x,y][:3] == color:
            pixels[x,y] = (0,0,0,0)
    return im
